package com.jt.tenant.app;

import android.app.Dialog;
import android.content.Context;
import android.support.multidex.MultiDex;

import com.amap.api.location.AMapLocation;
import com.jt.tenant.R;
import com.jt.tenant.action.InitDBAction;
import com.jt.tenant.action.LocationModular;
import com.jt.tenant.action.WeatherModular;
import com.jt.tenant.db.JTDB;
import com.jt.tenant.dialog.LoadDialog;
import com.jt.tenant.wxapi.LBJZWXPay;
import com.tencent.bugly.crashreport.CrashReport;
import com.zcx.helper.app.AppApplication;
import com.zcx.helper.http.Http;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.scale.d;
import com.zcx.helper.util.UtilAsyncBitmap;
import com.zcx.helper.util.UtilSDCard;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;
import okio.Buffer;

/**
 * Created by Administrator on 2016/1/30.
 */
public class JTApplication extends AppApplication {

    public static d ScaleScreenHelper;

    public static UtilAsyncBitmap UtilAsyncBitmap;

    public static JTPreferences jtPreferences;

    public static JTDB jtDB;

    public static WeatherModular WeatherModular;

    public static Context mContext;

    public static LocationModular locationModular;
    public static LBJZWXPay lbjzwxPay;
    public static Set<String> tag;
    public static String lon,lat;

    String cer = "-----BEGIN CERTIFICATE-----\n" +
            "MIIDxzCCAq+gAwIBAgIEUsFcvjANBgkqhkiG9w0BAQsFADCBkzELMAkGA1UEBhMC\n" +
            "WkgxFTATBgNVBAgTDGhlaWxvbmdqaWFuZzEQMA4GA1UEBxMHaGFlcmJpbjEdMBsG\n" +
            "A1UEChMUZGV2ZWxvcGVyLnR5ZmJveC5jb20xHTAbBgNVBAsTFGRldmVsb3Blci50\n" +
            "eWZib3guY29tMR0wGwYDVQQDExRkZXZlbG9wZXIudHlmYm94LmNvbTAeFw0xNjEx\n" +
            "MDcwNTM1NDBaFw0xNzAyMDUwNTM1NDBaMIGTMQswCQYDVQQGEwJaSDEVMBMGA1UE\n" +
            "CBMMaGVpbG9uZ2ppYW5nMRAwDgYDVQQHEwdoYWVyYmluMR0wGwYDVQQKExRkZXZl\n" +
            "bG9wZXIudHlmYm94LmNvbTEdMBsGA1UECxMUZGV2ZWxvcGVyLnR5ZmJveC5jb20x\n" +
            "HTAbBgNVBAMTFGRldmVsb3Blci50eWZib3guY29tMIIBIjANBgkqhkiG9w0BAQEF\n" +
            "AAOCAQ8AMIIBCgKCAQEAnVc7XPn5/Kx98RPgbyJdFEXckoXY9Za8/eHAUHa8QYB2\n" +
            "LoR7jn46WIzkqIb2qbZsPZm6dEE25EeYbTdUjQWojMgsxTyAXxb8AkJ6U4EbsKnF\n" +
            "6CdZ9Zs2FUn9UaCdMNekKwFiPUlrqxBa2PPhAi4SMbVHEW9pUOVvBRpMEvHm38ii\n" +
            "gYjzpLxrOXLGw4YAkHkRj8FVjqFGpSdYvxUq8JLXPsQadXZ6NGHPZ4q8zw6bIzfs\n" +
            "makaM5SkFLjI7YJuZ3lvdKYZmfjOoVvX/Ro1Pi+pHUTdblqLqjqMV8NMkpQ0wqP9\n" +
            "j3DraRe16CNv3pEAJ1WfQecnxfS4WhZxlYNxUOc9AQIDAQABoyEwHzAdBgNVHQ4E\n" +
            "FgQUdz95DROLfS/8ljcE6OHzk2XGCvswDQYJKoZIhvcNAQELBQADggEBAGeTPA++\n" +
            "2ETeBXuZ+u4hnWioVsBVjuXUgBEvOPhV8UUTtGM217vaTje6Yj0nJK8Nk3K2JrPG\n" +
            "1JV44/tnMduglBaWQY6jeH5530O2VT+JqY+6Lv9tz9RvKpz0mA7gobkQs6RfVG0o\n" +
            "8ED51aLXpPLYJ7gfp1piFuAmO6v9mwlUs+tAXOeWmHpNBCx9YAznlrGqyjdubT0h\n" +
            "GhI5RSg+arpThpVYeNNR/cdMTbnyJWb8iKAwWAqWReIDEAPc0oz04eGOg0e5gSIA\n" +
            "rpPWRq8y0M+aq7chyTSFilgFK/L8T57779PCy1hojeycdkw98MQ+1brorEmm9HK5\n" +
            "Dfx84s6PkNOPdzk=\n" +
            "-----END CERTIFICATE-----";

    @Override
    public void onCreate() {

        mContext = getApplicationContext();

        super.onCreate();

        ShareSDK.initSDK(mContext,"1ac6686bbfc0d");

        tag = new HashSet<>();
        tag.add("1");

        CrashReport.initCrashReport(this, "900018621", false);

        JPushInterface.setDebugMode(true);

        JPushInterface.init(this);

//        Http.getInstance().setIsLog(false);

        Http.getInstance().setIsLog(true);

        lbjzwxPay = new LBJZWXPay(this);

        Http.getInstance().setCache(UtilSDCard.getSDCardPath() + "jt_cache", 10 * 1024 * 1024);
//
//        // 添加https证书
//        try {
//            String[]  certFiles=this.getAssets().list("certs");
//            if (certFiles != null) {
//                for (String cert:certFiles) {
//                    InputStream is = getAssets().open("certs/" + cert);
//                    NetConfig.addCertificate(is); // 这里将证书读取出来，，放在配置中byte[]里
//                }
//            }
//        } catch (IOException ioe) {
//            ioe.printStackTrace();
//        }
//
//        // 添加证书
//
//        List<InputStream> certificates = new ArrayList<>();
//
//        List<byte[]> certs_data = NetConfig.getCertificatesData();
//
//        // 将字节数组转为数组输入流
//
//        if (certs_data != null && !certs_data.isEmpty()) {
//
//            for (byte[] bytes:certs_data) {
//
//                certificates.add(new ByteArrayInputStream(bytes));
//
//            }
//
//        }
//
//        SSLSocketFactory sslSocketFactory = getSocketFactory(certificates);
//
//        Http.getInstance().setSslSocketFactory(sslSocketFactory);

//        setCertificates(cer);

        Http.getInstance().setOnStartEndCreateDialog(new Http.OnStartEndCreateDialog() {

            @Override
            public Dialog onCreate(Context context) {

                return new LoadDialog(context);

            }

            @Override
            public void show(Dialog dialog) {

                dialog.show();

            }

            @Override
            public void dismiss(Dialog dialog) {

                dialog.dismiss();

            }

        });

        ScaleScreenHelper = ScaleScreenHelperFactory.create(this, 720);

        UtilAsyncBitmap = new UtilAsyncBitmap(this, "jt", R.id.key_id, R.mipmap.loading);

        jtPreferences = new JTPreferences(this);

        jtDB = InitDBAction.initjtDB(this);

        WeatherModular = new WeatherModular(this);

        locationModular = new LocationModular(this);

        locationModular.addOnLocateionChangeCallBack(new LocationModular.OnLocateionChangeCallBack(){

            @Override
            public void onLocation(AMapLocation aMapLocation) {

                WeatherModular.setCity(aMapLocation.getCity().replace("市", ""));

            }

        });

    }


    /**

     * 添加证书

     *

     * @param certificates

     */

    private static SSLSocketFactory getSocketFactory(List<InputStream> certificates) {


        try {

            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            keyStore.load(null);


            try {

                for (int i = 0, size = certificates.size(); i < size; ) {

                    InputStream certificate = certificates.get(i);

                    String certificateAlias = Integer.toString(i++);

                    keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));


                    if (certificate != null)

                        certificate.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }


            SSLContext sslContext = SSLContext.getInstance("TLS");


            TrustManagerFactory trustManagerFactory =

                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());


            trustManagerFactory.init(keyStore);

            sslContext.init

                    (

                            null,

                            trustManagerFactory.getTrustManagers(),

                            new SecureRandom()

                    );


            return sslContext.getSocketFactory();


        } catch (Exception e) {

            e.printStackTrace();

        }


        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void setCertificates(String cer){

        setCertificates(new Buffer().writeUtf8(cer).inputStream());

    }

    public void setCertificates(InputStream... m){

        try{

            CertificateFactory d = CertificateFactory.getInstance("X.509");

            KeyStore k = KeyStore.getInstance(KeyStore.getDefaultType());

            k.load(null);

            int i = 0;

            for (InputStream e : m){

                String r = Integer.toString(i++);

                k.setCertificateEntry(r, d.generateCertificate(e));

                try {

                    if (e != null){

                        e.close();

                    }

                } catch (IOException f) {

                    f.printStackTrace();

                }

            }

            SSLContext s = SSLContext.getInstance("TLS");

            TrustManagerFactory t = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            t.init(k);

            s.init(null, t.getTrustManagers(), new SecureRandom());

            Http.getInstance().setSslSocketFactory(s.getSocketFactory());

        } catch (Exception e){

            e.printStackTrace();

        }

    }

}
